﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Commands;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Models.ICModels;
using Casamiel.API.Application.Services;
using Casamiel.API.Infrastructure;
using Casamiel.Application;
using Casamiel.Application.Commands;
using Casamiel.Application.Commands.IC;
using Casamiel.Application.Commands.Wechat;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Request;
using Casamiel.Domain.Request.GroupPurchase;
using Casamiel.Domain.Request.IC;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.GroupPurchase;
using Casamiel.Domain.Response.IC;
using Enyim.Caching;
using MediatR;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers
{

	/// <summary>
	/// Store service controller.
	/// </summary>
	[ApiVersionNeutral]
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("any")]
    public class StoreServiceController : BaseController
    {
        private readonly NLog.ILogger logger = NLog.LogManager.GetLogger("OrderService");
        private readonly NLog.ILogger errorlogger = NLog.LogManager.GetLogger("ModelStateService");
        private readonly IMemberCardService _memberCardService;
        private readonly IStoreService _storeService;
        private readonly IMemberService _memberService;
        private readonly IIcApiService _icApiService;
        private readonly Casamiel.Application.ICasaMielSession _session;
        private readonly IPaymentService _paymentService;
        private readonly List<Common.MiniAppSettings> _listminiAppSettings;
        private readonly IStoreApiService _storeApiService;
        private readonly IOrderService _order;
        private readonly string _apitoken;
        private readonly IRefundService _refundService;
        private readonly ICacheService _cacheService;
        private readonly IErrorLogService _errorLogService;
        private readonly IUserLogService _userLogService;
        private readonly IMemcachedClient _memcachedClient;
        private readonly AppRegCard _appRegCard;
        private readonly IMemberCouponRecordService _memberCouponRecordService;
        private readonly IMediator _mediator;
        private readonly IHttpClientFactory _clientFactory;
        private readonly CasamielSettings _casamielSettings;
        private readonly IWxService _wxService;
        private readonly IProductService _productService;
        private readonly string _memcachedPre;
        private readonly string _apitname;
        private readonly INetICService _netICService;
        private readonly IAllPayService _allPayService;
        private readonly IMallService _mallService;
        private readonly IMobileCheckCode _mobileCheckCode;

        private readonly IMemberCouponService _memberCouponService;
        private readonly AliyunSettings _aliyunSettings;
        //private readonly IStaffService _staffService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="mobileCheckCode"></param>
        /// <param name="storeService">Store service.</param>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="session">Session.</param>
        /// <param name="paymentService">Payment service.</param>
        /// <param name="mini">Mini.</param>
        /// <param name="memberCardService">Member card service.</param>
        /// <param name="refundService">Refund service.</param>
        /// <param name="storeApiService">Store API service.</param>
        /// <param name="snapshot">Snapshot.</param>
        /// <param name="cacheService">Cache service.</param>
        /// <param name="errorLogService">Error log service.</param>
        /// <param name="memcachedClient">Memcached client.</param>
        /// <param name="userLogService">User log service.</param>
        /// <param name="appRegCard">App reg card.</param>
        /// <param name="memberCouponRecord">Member coupon record.</param>
        /// <param name="mediator">Mediator.</param>
        /// <param name="clientFactory">Client factory.</param>
        /// <param name="wxService">Wx service.</param>
        /// <param name="order">Order.</param>
        /// <param name="productService">Product service.</param>
        /// <param name="allPayService">All pay service.</param>
        /// <param name="netICService">Net ICS ervice.</param>
        /// <param name="mallService">Mall service.</param>
        /// <param name="memberService"></param>
        /// <param name="memberCouponService"></param>
        /// <param name="aliyunsettings"></param>
        public StoreServiceController(IMobileCheckCode mobileCheckCode, IStoreService storeService, IIcApiService iicApiService, Casamiel.Application.ICasaMielSession session, IPaymentService paymentService, IOptionsSnapshot<List<Common.MiniAppSettings>> mini,
                                      IMemberCardService memberCardService, IRefundService refundService, IStoreApiService storeApiService, IOptionsSnapshot<CasamielSettings> snapshot,
                                      ICacheService cacheService, IErrorLogService errorLogService, IMemcachedClient memcachedClient, IUserLogService userLogService,
                                     IOptionsSnapshot<AppRegCard> appRegCard, IMemberCouponRecordService memberCouponRecord, IMediator mediator, IHttpClientFactory clientFactory,
                                      IWxService wxService, IOrderService order, IProductService productService, IAllPayService allPayService, INetICService netICService, IMallService mallService,
                                      IMemberService memberService, IMemberCouponService memberCouponService, IOptionsSnapshot<AliyunSettings> aliyunsettings)
        {
            if (mini == null) {
                throw new ArgumentNullException(nameof(mini));
            }

            if (snapshot == null) {
                throw new ArgumentNullException(nameof(snapshot));
            }

            if (appRegCard == null) {
                throw new ArgumentNullException(nameof(appRegCard));
            }

            _mobileCheckCode = mobileCheckCode;
            _storeService = storeService;
            _icApiService = iicApiService;
            _session = session;
            _paymentService = paymentService;
            _listminiAppSettings = mini.Value;
            //Configuration = configuration;
            _memberCardService = memberCardService;
            _refundService = refundService;
            _storeApiService = storeApiService;
            _apitoken = snapshot.Value.ApiToken;
            _apitname = snapshot.Value.ApiName;
            _memcachedPre = snapshot.Value.MemcachedPre;
            _cacheService = cacheService;
            _errorLogService = errorLogService;
            _memcachedClient = memcachedClient;
            _appRegCard = appRegCard.Value;
            _memberCouponRecordService = memberCouponRecord;
            _mediator = mediator;
            _userLogService = userLogService;
            _clientFactory = clientFactory;
            _casamielSettings = snapshot.Value;
            _wxService = wxService;
            _order = order;
            _productService = productService;
            _allPayService = allPayService;
            _netICService = netICService;
            _mallService = mallService;
            _memberService = memberService;
            _memberCouponService = memberCouponService;
            _aliyunSettings = aliyunsettings.Value;
        }

 

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<string>> CardMerge(string mobile)
        {

            var command = new CardMergeCommand (LoginInfo.Item3){ Mobile = mobile, RequestUrl = Request.GetShortUri(), UserIp = Request.GetUserIp() };
            var result = await _mediator.Send(command).ConfigureAwait(false);
            return result;
        }
         
       
        /// <summary>
        /// 拼团订单退款
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GroupPurchaseRefund([FromBody]RefundReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            if (data.Secrect != _apitoken) {
                return Ok(new { code = 99999, msg = "secrect无效" });
            }

            //var orderRefund = new OrderRefundReq { OrderCode = data.OrderCode, CancelReason = data.CancelReason.ToString() };
            var m = await _refundService.GroupPurchaseOrderRefund(data.OrderCode).ConfigureAwait(false);
            if (m.code == 0) {
                await _storeApiService.ChangeGrouponOrderStatusAsync(data.OrderCode, "", 6, 0);
            }
            return Ok(m);

        }
       
        

        /// <summary>
		/// 参与拼团页面详情(H5调用）
		/// </summary>
        /// <returns></returns>
		[HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<JoinGroupPurchseOrderResponse>> GetJoinGroupPurchaseOrderDetail(GetOrderDetailRequest request)
        {

            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }

            var cmd = new Casamiel.Application.Commands.GroupPurchase.JoinGroupPurchaseOrderDetailCommand(request.OrderCode,LoginInfo.Item3);
            var rsp = await _mediator.Send(cmd).ConfigureAwait(false);
            return rsp;
        }


        /// <summary>
        /// 拼团活动详情H5调用）
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<GrouponActivityDetailResponse>> GetDetail(GetGroupActivityDetailRequest req)
        {
            var cmd = new Casamiel.Application.Commands.GroupPurchase.GetDetailCommand(req.GrouponId,LoginInfo.Item3);
            var rsp = await _mediator.Send(cmd).ConfigureAwait(false);
            return rsp;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        [Route("[action]")]
        public IActionResult Upgrade()
        {
            return Ok(new { Code = 9999, msg = "抱歉系统升级中，预计11月7日7点恢复正常", });
        }
        /// <summary>
        /// 幸福卡信息查看
        /// </summary>
        /// <param name="req"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<IcqrcodequeryRsp>> Icqrcodequery([FromBody]IcqrcodequeryReq req, [FromHeader(Name = "u-token")] string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }

            if (token != _apitoken) {
                return new BaseResult<IcqrcodequeryRsp>(null, 99999, "token无效");
            }
            var e = await _icApiService.icqrcodequery("", req.QrCodeNO).ConfigureAwait(false);
            if (e.code == 0 || e.code == 322) {
                var info = JsonConvert.DeserializeObject<IcqrcodequeryRsp>(e.content);
                if (info != null) {
                    info.StateDesc = e.code == 0 ? "未使用" : "已使用";
                }
                return new BaseResult<IcqrcodequeryRsp>(info, 0, "");
            }
            return new BaseResult<IcqrcodequeryRsp>(null, e.code, e.msg);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="days"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetResponseTimeService(int days)
        {
            if (days > 0) {
                days = 0;
            }
            FileStream fs = new FileStream($"{AppContext.BaseDirectory}//logs//{DateTime.Now.AddDays(-1 + days).ToString("yyyy-MM-dd")}//ResponseTimeService.log", FileMode.Open, FileAccess.Read);
            List<string> list = new List<string>();
            StreamReader sr = new StreamReader(fs);
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
            string temp = await sr.ReadLineAsync().ConfigureAwait(false);
            Regex reg = new Regex(@"执行时间(\d*)");

            while (temp != null) {
                Match match = reg.Match(temp);
                //list.Add(match.Groups[1].Value);
                if (match.Groups[1].Value.ToInt32(0) > 800) {
                    list.Add(temp);
                }

                temp = await sr.ReadLineAsync().ConfigureAwait(false);
            }
            //关闭此StreamReader对象 
            sr.Close();
            fs.Close();
            return Ok(list);

        }


        

        /// <summary>
        /// Removes the memcached.
        /// </summary>
        /// <returns>The memcached.</returns>
        /// <param name="a">The alpha component.</param>
        [HttpPost]
        [Route("[action]")]
        public IActionResult RemoveMemcached(string a)
        {
            var trynum = _memcachedClient.Remove(a);
            return Ok(trynum);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="req"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetBaseQuery([FromBody] BasedataqueryReq req, [FromHeader(Name = "u-token")]string token)
        {
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            var d = await _icApiService.BasedataQuery(req).ConfigureAwait(false);
            var shopno = "";

            var d1 = JsonConvert.DeserializeObject<JArray>(d.content);
            if (d1.Count > 0) {
                shopno = d1[0]["no"].ToString();
            }

            return Ok(shopno);
        }
        /// <summary>
        /// Gets the reg info by mobile.
        /// </summary>
        /// <returns>The reg info by mobile.</returns>
        /// <param name="mobile">Mobile.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetRegInfoByMobile(string mobile)
        {
            var list = await _userLogService.GetListByMobileAsnyc<ICasaMielSession>(mobile).ConfigureAwait(false);
            return Ok(list);
        }

        /// <summary>
        /// 预订单制作完成发送订阅消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<string>> SendPreOrderSubcribeMessage(SendPreOrderSubcribeMessagRequest request, [FromHeader(Name = "u-token")] string token)
        {
            if (request is null) {
                throw new ArgumentNullException(nameof(request));
            }

            if (token != _apitoken) {
                return new BaseResult<string>("", 99999, "token无效");
            }
            var cmd = new ProductionCompletedSubscribeCommand { Mobile = request.Mobile,OrderCode=request.OrderCode };
            cmd.Data = new string[] { request.TakeCode, "制作完成", request.StoreName, request.Address };
            await _mediator.Send(cmd).ConfigureAwait(false);
            return new BaseResult<string>("", 0, "");

        }

        /// <summary>
        /// Creates the shop QRC ode.
        /// </summary>
        /// <returns>The shop QRC ode.</returns>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> CreateShopQRCode([FromHeader(Name = "u-token")]string token)
        {
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
             
            var appId = "wx3961257c61049cb4";
            if (_apitname == "hgspApi") {
                appId = "wx40b3cfa5a184457a";
            }
            var _cacheKey = _memcachedPre + Constant.MINIAPPPTOKEN + appId;
            var access_token = await _memcachedClient.GetValueAsync<string>(_cacheKey).ConfigureAwait(false);

            if (string.IsNullOrEmpty(access_token)) {
                var miniappentity = await _wxService.FindAsync<ICasaMielSession>(appId).ConfigureAwait(false);
                if (miniappentity == null) {
                    throw new Exception("小程序未配置");
                }
                string url = "cgi-bin/token?"; //grant_type=client_credential&appid=APPID&secret=APPSECRET";//https://api.weixin.qq.com/
                string param = string.Format(CultureInfo.CurrentCulture, "appid={0}&secret={1}&grant_type={2}", appId, miniappentity.Secret, "client_credential");
                var client = _clientFactory.CreateClient("weixin");
                string result = "";
                using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, url + param)) {
                    using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {

                        if (response.IsSuccessStatusCode) {
                            result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        }
                    }
                }

                var wxopenInfo = JsonConvert.DeserializeObject<dynamic>(result);
                access_token = wxopenInfo.access_token;

                // long expires_in = wxopenInfo.expires_in;
                await _memcachedClient.AddAsync(_cacheKey, access_token, 7000).ConfigureAwait(false);
            }
            if (string.IsNullOrEmpty(access_token)) {
                return Ok(false);
            }
            var list = await _storeService.GetAllStoreByNameAsync<ICasaMielSession>("").ConfigureAwait(false);
            foreach (var item in list) {
                //if (item.RelationId != 686326) {

                //    continue;
                //}
                await GetQRCode(item.RelationId.ToString(CultureInfo.CurrentCulture), item.StoreName, access_token).ConfigureAwait(false);
            }

            return Ok(list.Count);
        }
        /// <summary>
        /// Gets the QRC ode.
        /// </summary>
        /// <returns>The QRC ode.</returns>
        /// <param name="shopid">Shopid.</param>
        /// <param name="storename">Storename.</param>
        /// <param name="a">The alpha component.</param>
        private async Task GetQRCode(string shopid, string storename, string a = "")
        {
            // string a = "18_6_xT5j-S97yjVxzvFuD5w-ylG9SKavZdE6AD2tnfAt_eszaK3vUj_qnWJq4XGChO5DGEjsvl-gxoquMjBBGZ9RFKB33gDpxA_DU1ymIzZ9dSZgxwkr5mwj_HQ2AZXJjAAAJHT";
            string path = $"{AppContext.BaseDirectory}//logs//casashop//{shopid}.png";
            var client = _clientFactory.CreateClient("");
            using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={a}")) {
                var data = new { scene = $"shopid={shopid}", width = 1280 };
                requestMessage.Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json");
                using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                    if (response.IsSuccessStatusCode) {
                        using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) {
                            byte[] bytes = new byte[stream.Length];
                            stream.Read(bytes, 0, bytes.Length);
                            // 设置当前流的位置为流的开始
                            stream.Seek(0, SeekOrigin.Begin);
                            await System.IO.File.WriteAllBytesAsync(path, bytes).ConfigureAwait(false);

                        }

                        // return File(result, "image/jpeg");
                    }
                }
            }
        }
        /// <summary>
        /// Gets the member info.
        /// </summary>
        /// <returns>The member info.</returns>
        /// <param name="req">Req.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetMemberInfo([FromBody] GetGetMemberInfoReq req)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }

            var pid = 35;
            if (_casamielSettings.ApiName == "hgspApi") {
                pid = 30;
            }
            if (_casamielSettings.ApiName == "casamielnetwork") {
                var cmd = new CheckPermissionCommand(pid, req.Token);
                var s = await _mediator.Send(cmd).ConfigureAwait(false);
                if (!s) {
                    return Ok(new { code = 9999, msg = "没有权限" });
                }
            }
            var commond = new GetMemberInfoCardInfoCommand(req.Mobile, req.CardNO, LoginInfo.Item3);
            var reulst = await _mediator.Send(commond).ConfigureAwait(false);
            return Ok(reulst);

        }
        
        
        /// <summary>
        /// Getshiops the sce.
        /// </summary>
        /// <returns>The sce.</returns>
        /// <param name="name">Name.</param>
        [HttpPost]
        [Route("[action]")]
        public IActionResult GetshiopSce(string name)
        {
            Regex reg = new Regex(@"shopid=(\d*)");
            //例如我想提取记录中的NAME值
            Match match = reg.Match(name);
            string value = match.Groups[1].Value;
            return Ok(new { name = value });
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetUnPayOrder()
        {
            var list = await _order.GetUnPayOrderListAsync<Casamiel.Application.ICasaMielSession>(-10).ConfigureAwait(false);
            foreach (var item in list) {
                var _cardno = "";
                var cardlist = await _memberCardService.GetListAsync<Casamiel.Application.ICasaMielSession>(item.Mobile).ConfigureAwait(false);

                if (cardlist != null && cardlist.Where(c => c.IsBind == true).Count() == 2) {
                    var vipcard = cardlist.Where(c => c.IsBind == true).FirstOrDefault();
                    if (vipcard != null) {
                        _cardno = vipcard.CardNO;
                    }
                }
                if (string.IsNullOrEmpty(_cardno)) {
                    foreach (var c in cardlist) {
                        if (c.IsBind) {
                            _cardno = c.CardNO;
                            break;
                        }
                    }
                }
                var cmd = new CancelOrderMemberCouponCommand { OrderCode = item.OrderCode };
                await _mediator.Publish(cmd).ConfigureAwait(false);
                var command = new CancelOrderCommand(item.OrderCode, _cardno);
                var result = await _mediator.Send(command).ConfigureAwait(false);
               
            }
            return Ok(list);
        }

        /// <summary>
        /// Orderpickup the specified req.
        /// </summary>
        /// <returns>The orderpickup.</returns>
        /// <param name="req">Req.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Orderpickup([FromBody]OrderpickupReq req)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }

            if (req.Secrect != _apitoken) {
                return Ok(new { code = 99999, msg = "secrect无效" });
            }
            IcorderpickupReq dto = new IcorderpickupReq() {
                Phoneno = req.Mobile,
                Tradeno = req.Tradeno
            };
           
            var re = await _icApiService.Icorderpickup(dto).ConfigureAwait(false);
            logger.Trace($"icorderpickup:{JsonConvert.SerializeObject(dto)},Result:{JsonConvert.SerializeObject(re)}");
            if (re.code == 0) {
                var jobject = JsonConvert.DeserializeObject<JObject>(re.content);
                var billno = jobject["billno"].ToString();
                try {
                    var cmd = new InvoiceOpeningByTradeNOCommand { TradeNO = req.Tradeno };
                    var rsp = await _mediator.Send(cmd).ConfigureAwait(false);
                    logger.Error($"orderpick:{req.Tradeno},{rsp}");
                } catch (TaskCanceledException ex) {
                    logger.Error($"orderpick:{ex.StackTrace}");
                }
                return Ok(new { code = 0, billno });
            } else {
                return Ok(re);
            }
        }

        //[HttpPost]
        //[Route("[action]")]
        //public async  Task <IActionResult>Test(){
        //    await _memberCardService.Tes<ICasaMielSession>();
        //    return Ok("");
        //}


        /// <summary>
        /// 一网烘培退货
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="payinfo"></param>
        /// <returns></returns>
        private async Task<Zmodel> Consumeback(OrderBaseEntity entity, PaymentRecord payinfo)
        {
            
            var backdto = new IcConsumeBackReq { Tradeno = payinfo.IcTradeNO, Phoneno = payinfo.Mobile };
            logger.Trace($"{JsonConvert.SerializeObject(backdto)}");

            var re = await _icApiService.Icconsumeback(backdto).ConfigureAwait(false);
            if (re.code == 0 || re.code == 205) {
                JObject obj = JsonConvert.DeserializeObject<JObject>(re.content);
                logger.Trace($"icconsumeback:{re.content}");
                //if (re.code == 0)
                //{
                logger.Trace($"OrderCode:{entity.OrderCode},tradeno_origin:{obj["tradeno_origin"].ToString()},tradeno:{obj["tradeno"].ToString()},");
                var billno = obj["tradeno"].ToString();
                entity.ResBillNo = billno;
                if (entity.OrderType == 2) {
                    using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                        entity.CloseTime = DateTime.Now;
                        entity.OrderStatus = (int)OrderStatus.Cancelled;

                        var s = await _order.OrderBaseUPdateAsync(entity, uow).ConfigureAwait(true);
                        var take = await _order.UpdateOrderTakeStatus(entity.OrderBaseId, -1, billno, uow).ConfigureAwait(true);
                        var dis = await _order.UpdateOrderDiscountStatus(entity.OrderBaseId, 1, uow).ConfigureAwait(true);
                    }
                } else {
                    using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                        entity.CloseTime = DateTime.Now;
                        entity.OrderStatus = (int)OrderStatus.Cancelled;
                        var s = await _order.OrderBaseUPdateAsync(entity, uow).ConfigureAwait(false);
                        //var take = await _storeService.UpdateOrderTakeStatus(entity.OrderBaseId, -1, billno, uow);
                        //var dis = await _storeService.UpdateOrderDiscountStatus(entity.OrderBaseId, 1, uow);
                    }
                }
                //}
            }
            return re;
        }

        /// <summary>
        /// Refund the specified data.
        /// </summary>
        /// <returns>The refund.</returns>
        /// <param name="data">Data.</param>
        /// <remarks>
        /// {"orderCode":"","CancelReason":"","secrect":""}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Refund([FromBody]RefundReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            if (data.Secrect != _apitoken) {
                return Ok(new { code = 99999, msg = "secrect无效" });
            }
            var cmd = new CancelMemberCouponCommand("", data.OrderCode, 1, 6);
            var rsp = await _mediator.Send(cmd).ConfigureAwait(false);
            if (rsp.Code != 0) {
                return Ok(rsp);
            }
            var command = new CancelOrderMemberCouponCommand { OrderCode = data.OrderCode };
            await _mediator.Publish(command).ConfigureAwait(false);
            var orderRefund = new OrderRefundReq { OrderCode = data.OrderCode, CancelReason = data.CancelReason.ToString() };
            var m = await _refundService.OrderRefund(orderRefund).ConfigureAwait(false);
            return Ok(m);

        }


        /// <summary>
        /// 店标二维码
        /// {"shopid":"","secrect":""}
        /// </summary>
        /// <returns>The icqrcodecreate.</returns>
        /// <param name="data">Data.</param>
        /// <remarks></remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Icqrcodecreate([FromBody] IcQrcodecreateReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            if (data.Secrect != _apitoken) {
                return Ok(new { code = 99999, msg = "secrect无效" });
            }
            var dto = new IcQrcodeCreateReq { Shopid = data.Shopid.ToInt32(0), Qrcodetype = "11" };
            var model = await _icApiService.Icqrcodecreate(dto).ConfigureAwait(false);
            return Ok(model);//
        }
        /// <summary>
        /// 微信日志记录
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <remarks>{"msg":"","secrect":"","version":""}</remarks>
        [HttpPost]
        [Route("[Action]")]
        public IActionResult Errorlog([FromBody] ErrorlogReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            if (data.Secrect != _apitoken) {
                return Ok(new { code = 99999, msg = "secrect无效" });
            }
            var userAgent = string.IsNullOrEmpty(Request.Headers["User-Agent"].ToString()) ? Request.Headers["UserAgent"].ToString() : Request.Headers["User-Agent"].ToString();

            //errorlogger.Error($"userAgent:{userAgent},ip:{Request.GetUserIp()},error:{data["msg"].ToString()}");
            var version = data.Version;
            errorlogger.Error($"version:{version},userAgent:{userAgent},ip:{Request.GetUserIp()},error:{data.Msg}");
            return Ok(new { code = 0, msg = "" });
        }


        /// <summary>
        /// Gets the base IDB y sku.
        /// </summary>
        /// <returns>The base IDB y sku.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>{"SkuId":""}</remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetBaseIDBySku([FromBody]GetBaseIDBySkuReq data, [FromHeader(Name = "u-token")]string token)
        {
            if (data is null) {
                throw new ArgumentNullException(nameof(data));
            }

            logger.Trace($"GetBaseIDBySku:{JsonConvert.SerializeObject(data)}");
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }

            var result = await _storeApiService.GetGroupIdAsync(data.SkuId.ToInt32(0)).ConfigureAwait(false);
            if (result.IsSuccess) {
                return Ok(new { code = 0, content = new { eDishCode = $"{result.Data}" }, msg = "" });
            } else {
                return Ok(new { code = 999, msg = result.ResultRemark });
            }
            //return Ok(new { code = 0, content = new { eDishCode = $"{result}" },msg=""});
            //var rnt = JObject.Parse(result);
            //if (rnt["ResultNo"].ToString() == "00000000")// "ResultNo": "00000000",
            //{
            //    return Ok(new { code = 0, content = new { eDishCode = rnt["Data"].ToString() }, msg = "" });
            //} else {
            //    return Ok(new { code = 999, msg = rnt["ResultRemark"].ToString() });
            //}
        }
        /// <summary>
        /// GetDrinksGoodsId
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetDrinksGoodsId([FromHeader(Name = "u-token")]string token)
        {
            if (token != _apitoken) {
                //return new BaseResult<List<string>>(null, 9999, "token无效");
                return Ok(new { code = 99999, msg = "token无效" });
            }
            var cmd = new GetDrinksGoodsIdsCommand();
            var list = await _mediator.Send(cmd).ConfigureAwait(false);
            
            return Ok(new { code = 0, content = JsonConvert.SerializeObject(list), msg = "" });
        }
        private async Task GetIndexGoodsList(int storeid)
        {
            string ckey = Constant.INDEXGOODSLIST + $"{storeid}";
            var entity = await _cacheService.GetAsync<List<IndexGoods>>(ckey).ConfigureAwait(false);
            if (entity == null) {
                entity = await _storeApiService.GetIndexGoodsList(storeid).ConfigureAwait(false);
                if (entity != null) {
                    await _cacheService.AddAsync(ckey, entity, TimeSpan.FromDays(1), true).ConfigureAwait(false);
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> SetStoreIndexGoodsList([FromHeader(Name = "u-token")]string token)
        {
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            //var storelist = await _storeService.GetAllStore<ICasaMielSession>();
            //var ckey = "";
            //var entity =new  List<IndexGoods>();

            ParallelLoopResult result = Parallel.For(1, 150, async i => {
                await GetIndexGoodsList(i).ConfigureAwait(false);
                //Console.WriteLine("迭代次数：{0},任务ID:{1},线程ID:{2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
                //Thread.Sleep(10);
            });
            var msg = $"是否完成:{result.IsCompleted}";
            msg += $"最低迭代:{result.LowestBreakIteration}";

            await Task.Run(() => msg).ConfigureAwait(false);
            return Ok(new { code = 0, msg });
        }
        /// <summary>
        /// Gets all good base.
        /// </summary>
        /// <returns>The all good base.</returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetAllGoodBase()
        {
            var list = await _productService.GetGoodBaseListAsync<Casamiel.Application.ICasaMielSession>().ConfigureAwait(false);
            IcPriceReq data = new IcPriceReq {
                Product = new List<ProductItemReq>()
            };
            foreach (var item in list) {
                data.Product.Add(new ProductItemReq { Pid = $"{item.RelationId}" });
            }
            var zmodel = await _icApiService.ProductStockQuery(data).ConfigureAwait(false);
            for (int i = 0; i < zmodel.product.Count; i++) {
                var aa = list.Find(cw => cw.RelationId.ToString(CultureInfo.CurrentCulture) == zmodel.product[i].pid);
                if (aa != null) {
                    zmodel.product[i].title = aa.Title;
                }

            }
            var alist = new List<GoodBaseEntity>();
            var msg = "";
            foreach (var item in list) {
                if (zmodel.product.Any(p => p.pid == item.RelationId.ToString(CultureInfo.CurrentCulture))) {
                    msg += $",{item.RelationId}";
                }
                var entit = zmodel.product.Find(p => p.pid == item.RelationId.ToString(CultureInfo.CurrentCulture));
                if (entit == null) {
                    alist.Add(item);
                }

            }
            return Ok(new { zmodel, V1 = alist, zcount = zmodel.product.Count, pcout = list.Count, msg });
        }

        /// <summary>
        /// Gets the card balace.
        /// </summary>
        /// <returns>The card balace.</returns>
        /// <param name="cardno">Cardno.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetCardBalace(string cardno, [FromHeader(Name = "u-token")]string token)
        {
            Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CreateSpecificCulture("en-US"))}");
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            var d = await _icApiService.Iclessquery(cardno, 15).ConfigureAwait(false);
            return Ok(d);

        }

        /// <summary>
        /// Addgetamout the specified req and token.
        /// </summary>
        /// <returns>The addgetamout.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Addgetamout([FromBody]AddTicketsReq req, [FromHeader(Name = "u-token")]string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }

            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }

            var d = await _icApiService.Icticketlargess(req).ConfigureAwait(false);
            if (d.code == 0) {
                logger.Trace($"{JsonConvert.SerializeObject(d)}");
                var jobj = JsonConvert.DeserializeObject<JObject>(d.content);

                var coupon = new MemberCouponRecord { Mobile = req.Phoneno, CardNO = req.Cardno, CreateTime = DateTime.Now, Largessno = jobj["largessno"].ToString(), RequestInfo = JsonConvert.SerializeObject(req) };
                await _memberCouponRecordService.AddAsync<Casamiel.Application.ICasaMielSession>(coupon).ConfigureAwait(false);
            } else {
                var coupon = new MemberCouponRecord { Mobile = req.Phoneno, CardNO = req.Cardno, CreateTime = DateTime.Now, Largessno = d.code.ToString(CultureInfo.CurrentCulture) + "    " + d.msg, RequestInfo = JsonConvert.SerializeObject(req) };
                await _memberCouponRecordService.AddAsync<Casamiel.Application.ICasaMielSession>(coupon).ConfigureAwait(false);
            }

            return Ok(d);

        }
       
       

        /// <summary>
        /// Gets the product.
        /// </summary>
        /// <returns>The product.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>{"RelationId":2222}</remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetProduct([FromBody] StoreGetProductReq data, [FromHeader(Name = "u-token")]string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            var a = await _storeService.GetDetailV2ByReleationIdAsync<Casamiel.Application.ICasaMielSession>(data.RelationId).ConfigureAwait(false);
            return Ok(new { code = 0, content = a });
        }

        

    }
}
